package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.dao.impl.AccountDaoImpl;
import com.powernode.bank.exception.MoneyNotEnoughException;
import com.powernode.bank.exception.TransferException;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import com.powernode.bank.util.GenerateDaoProxy;
import com.powernode.bank.util.sqlSessionUtil;
import jakarta.servlet.annotation.WebServlet;
import org.apache.ibatis.session.SqlSession;



public class AccountServiceImpl implements AccountService {

//    private AccountDao accountDao = new AccountDaoImpl();
//    private AccountDao accountDao = (AccountDao)GenerateDaoProxy.generate(sqlSessionUtil.openSession(), AccountDao.class);
        private AccountDao accountDao = sqlSessionUtil.openSession().getMapper(AccountDao.class);

    public void transfer(String fromActno, String toActno, Double money) throws MoneyNotEnoughException, TransferException {

        SqlSession sqlSession = sqlSessionUtil.openSession();

        Account fromAccount = accountDao.selectByActno(fromActno);

        if (fromAccount.getBalance() < money){
            throw new MoneyNotEnoughException("余额不足");
        }
        Account toAct = accountDao.selectByActno(toActno);
        fromAccount.setBalance(fromAccount.getBalance()-money);
        toAct.setBalance(toAct.getBalance()+money);
        int count = accountDao.updateBalance(fromAccount);

        count +=accountDao.updateBalance(toAct);
        if (count !=2){
            throw new TransferException("转账失败"   );
        }
        sqlSession.commit();
        sqlSession.close();
    }
}
